const router = require('koa-router')()
const util = require('../utils/util')
const Role = require('../models/roleSchema')

router.prefix('/role')

router.post('/init', (ctx) => {
  for (var i = 0; i < 20; i++) {
    const params = {
      roleName: `产品经理${i}`,
      remark: `交互产品经理${i}`,
    }
    Role.create(params)
  }

  ctx.body = util.success('初始化成功')
})

router.get('/allList', async (ctx) => {
  const { roleName } = ctx.request.query
  const { page, skipIndex } = util.pager(ctx.request.query)
  let params = {}
  if (roleName) params.roleName = roleName

  try {
    const query = Role.find(params)
    const list = await query.skip(skipIndex).limit(page.pageSize)
    const total = await Role.countDocuments(params)
    ctx.body = util.success({
      list,
      page: {
        ...page,
        total,
      },
    })
  } catch (error) {
    ctx.body = util.fail(error.stack)
  }
})

router.post('/operate', async (ctx) => {
  const { _id, action, ...params } = ctx.request.body
  let res, info

  try {
    if (action == 'add') {
      res = await Role.create(params)
      info = '创建成功'
    } else if (action == 'edit') {
      params.updateTime = new Date()
      res = await Role.findByIdAndUpdate(_id, params)
      info = '编辑成功'
    } else {
      res = await Role.findByIdAndRemove(_id)
      info = '删除成功'
    }
    ctx.body = util.success('', info)
  } catch (error) {
    ctx.body = util.fail(error.stack)
  }
})

// 权限设置
router.post('/update/permission', async (ctx) => {
  const { _id, permissionList } = ctx.request.body
  try {
    let params = {
      permissionList,
      updateTime: new Date(),
    }
    let res = await Role.findByIdAndUpdate(_id, params)
    ctx.body = util.success(res, '权限设置成功')
  } catch (err) {
    ctx.body = util.fail('权限设置失败：' + err.stack)
  }
})

module.exports = router
